using System.Security.Cryptography;
using System.Text;

namespace Medical.Infrastructrue.Utils
{
    /// <summary>
    /// 密码加密工具类
    /// </summary>
    public static class PasswordHasher
    {
        /// <summary>
        /// 使用SHA256算法对密码进行哈希加密
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns>Base64编码的哈希值</returns>
        /// <exception cref="ArgumentException">当密码为空或空白时抛出</exception>
        public static string HashPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
                throw new ArgumentException("密码不能为空", nameof(password));

            using (var sha256 = SHA256.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(password);
                var hash = sha256.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }

        /// <summary>
        /// 验证密码是否与哈希值匹配
        /// </summary>
        /// <param name="password">待验证的明文密码</param>
        /// <param name="hashedPassword">存储的哈希密码</param>
        /// <returns>如果密码匹配返回true，否则返回false</returns>
        public static bool VerifyPassword(string password, string hashedPassword)
        {
            if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(hashedPassword))
                return false;

            var hashOfInput = HashPassword(password);
            return hashOfInput == hashedPassword;
        }
    }
}

